/**
 * +----------------------------------------------------------------------
 * | xyui [  * | xyui [ 全端渐进式UI框架 ] ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2020 http://jiangruyi.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: jry <598821125@qq.com>
 * +----------------------------------------------------------------------
 * | 版权申明：此源码不是一个自由软件，是jry推出的私有源码，严禁在未经许可的情况下
 * | 拷贝、复制、传播、使用此源码的任意代码，如有违反，请立即删除，否则您将面临承担相应
 * | 法律责任的风险。如果需要取得官方授权，请联系官方QQ598821125。
*/

import vue from '@/main.js';
import store from '@/store';
let util = {};

// uni-app wrap
util.showToast = uni.showToast;
util.showModal = uni.showModal;
util.navigateTo = uni.navigateTo;
util.redirectTo = uni.redirectTo;
util.reLaunch = uni.reLaunch;
util.switchTab = uni.switchTab;
util.setStorageSync = uni.setStorageSync;
util.getStorageSync = uni.getStorageSync;
util.removeStorageSync = uni.removeStorageSync;
util.clearStorageSync = uni.clearStorageSync;

// 图片缓存xy-image依赖
util.imageCahceList = util.getStorageSync('xy-image-cahce');
if (util.imageCahceList.length == 0) {
    util.imageCahceList = new Object();
}
util.imageCache = function(url, complete = null) {
    // #ifdef H5
    return url;
    // #endif
    // #ifdef APP-PLUS || MP
    const key = (encodeURIComponent(url));
    try{
        if(!util.imageCahceList[key]) {
            uni.downloadFile({
                url: url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        let tempFilePath = res.tempFilePath;
                        uni.saveFile({
                            tempFilePath: tempFilePath,
                            success: function (res) {
                                let savedFilePath = res.savedFilePath;
                                util.imageCahceList[key] = savedFilePath;
                                util.setStorageSync('xy-image-cahce', util.imageCahceList);
                                complete && complete(savedFilePath);
                            }
                        });
                    }
                }
            });
            return url;
        }
        return util.imageCahceList[key];
    } catch(e) {
        console.log(e);
    }
    // #endif
}

// 获取token
util.getToken = function () {
    return store.state.user.token;
};

// 存储token
util.setToken = function (data) {
    return store.commit('user/setToken', data);
};

// 判断登录
util.isLogin = function() {
    if (!util.getToken()) {
        util.showModalLogin();
        return false;
    }
    return true;
}
util.showModalLogin = function() {
    uni.showModal({
        title: '提示',
        content: '登录超时，点击确定重新登录。',
        success: function (res) {
            if (res.confirm) {
                util.navigateTo({
                    url: '/pages/core/user/login'
                });
            } else if (res.cancel) {
            }
        }
    });
    return false;
}

// uploadFile
util.uploadFile = async function({
    driver = 'default',
    signUrl,
    url = '',
    filePath,
    fileExt = '',
    name = 'file',
    fileType = 'image',
    header = {},
    formData = {},
    success,
    fail,
    complete
}){
    console.log(filePath);
    let res0 = {};
    switch (driver){
        case 'upload_oss':
            if (!signUrl) {
                signUrl = '/v1/upload_oss/index/sign';
            }
            // 申请上传签名
            res0 = await util.request({
                url: signUrl,
                method: 'get',
                header: header
            });
            if (res0.code == 200) {
                url = res0.data.params.host;
                // 路径 + 文件名 + 扩展名
                // uniapp跟PC端不同，PC端可以直接得到文件名。
                res0.data.params.key = res0.data.params.key + res0.data.params.uniqidName + fileExt;
                formData = res0.data.params;
            } else {
                uni.showToast({
                    title: res0.msg,
                    duration: 1500
                });
                return;
            }
            break;
        default:
            header = {
                'Authorization': util.getToken()
            }
            break;
    }
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: url,
            filePath: filePath,
            name: name,
            fileType: fileType,
            header: header,
            formData: formData,
            success: (uploadFileRes) => {
                console.log(uploadFileRes.data);
                switch (driver) {
                    case 'upload_oss':
                        let res = new Object();
                        res.code = 200;
                        res.msg = '上传成功';
                        res.data = {
                            url: res0.data.params.host + '/' + res0.data.params.key
                        }
                        resolve(res);
                        break;
                    default:
                        let res1 = JSON.parse(uploadFileRes.data);
                        resolve(res1);
                        break
                }
            }
        });
    });
};

// request
util.request = function ({
    method = "GET",
    url,
    data,
    header,
    success,
    fail,
    complete
}) {
    // 请求
    if (0 != url.indexOf("http")) {
        url = store.state.app.baseUrl + url;
    }
    var _header = {
        'content-type': 'application/json',
        'Authorization': store.state.user.token
    };
    header = Object.assign(_header, header);
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: method,
            data: data,
            header: header,
            dataType: 'json',
            success: success,
            fail: (res) => {
                let ret = new Object();
                ret.code = 0;
                // ret.msg = res.errMsg
                ret.msg = '接口或网络异常';
                reject(ret);
            },
            complete: (res) => {
                // console.log('requestRes:', res);
                if (res.statusCode === 200) { //成功
                    if (res.data.code == 401) {
                        store.commit('user/setToken', '');
                        util.showModalLogin();
                        return false;
                    }

                    if (res.data.code != 200 && res.data.alert) {
                        switch (res.data.alert) {
                            case 'toast':
                                uni.showToast({
                                    icon: 'loading',
                                    title: res.data.msg
                                })
                                break;
                            case 'modal':
                                uni.showModal({
                                    title: '提示',
                                    content: res.data.msg,
                                    success: function (res) {}
                                });
                                break;
                        }
                        return false;
                    }
                    resolve(res.data);
                } else {
                    console.log('requestErr:', res);
                    let ret = new Object();
                    ret.code = 0;
                    ret.msg = res.errMsg;
                    reject(ret);
                }
            }
        })
    });
};

// 时间格式化
util.formatDate = function(time, fmt = 'yyyy-MM-dd hh:mm') {
    let date = '';
    if (typeof(time) == 'object' ) {
        date = time;
    } else if (typeof(time) == 'number' ) {
        date = new Date(time * 1000);
    } else {
        return time;
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : util.padLeftZero(str));
        }
    }
    return fmt;
};

util.padLeftZero = function (str) {
    return ('00' + str).substr(str.length);
};

// #ifdef H5
// 判断是否是微信浏览器的函数
util.runEnv = function (){
    var ua = window.navigator.userAgent.toLowerCase();
    // 是否在微信环境下
    if(ua.match(/MicroMessenger/i) == 'micromessenger' && ua.match(/wxwork/i) != 'wxwork'){
        return 'weixin-h5';
    }
    // 是否在企业微信环境下
    if(ua.match(/wxwork/i) == 'wxwork'){
        return 'wework-h5';
    }
    // 是否在PC环境下
    if(!(/Android|webOS|iPhone|iPod|BlackBerry/i.test(ua))) {
        return 'pc-h5';
    }
    return '';
}
// #endif

export default util;
